package com.woniu.zsd.shopping.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.shopping.model.SalesData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class SalesDataServiceImpl {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public SalesData getSalesDataFromRedis() {



        // 使用格式化日期字符串作为键来获取 Redis 中的数据
        String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String key = formattedDate+"_product_statistics";
        String salesDataJson = stringRedisTemplate.opsForValue().get(key);


        // 如果 Redis 中没有数据，返回 null 或者你可以抛出异常
        if (salesDataJson == null) {
            return null;
        }

        try {
            // 将 JSON 数据转换成 SalesData 对象
            return objectMapper.readValue(salesDataJson, SalesData.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
